package cn.schoolwow.quickdao.test.module.initial.service;

import cn.schoolwow.quickdao.QuickDAO;
import cn.schoolwow.quickdao.domain.DAO;
import cn.schoolwow.quickdao.domain.database.parent.DatabaseType;
import cn.schoolwow.quickdao.test.module.initial.flow.*;
import cn.schoolwow.quickflow.domain.FlowContext;
import cn.schoolwow.quickflow.domain.FlowDataFeature;
import cn.schoolwow.quickflow.dto.FlowContextDataRange;
import cn.schoolwow.quickflow.flow.BusinessFlow;
import com.zaxxer.hikari.HikariDataSource;

public class SetDAOFlow implements BusinessFlow {
    private static DAO dao;

    @Override
    public void executeBusinessFlow(FlowContext flowContext) throws Exception {
        if(null!=dao){
            flowContext.putInstanceData(dao, DAO.class);
            return;
        }
        setDataSource(flowContext);
        setDAO(flowContext);
    }

    @Override
    public String name() {
        return "设置DAO对象";
    }

    private void setDataSource(FlowContext flowContext){
        DatabaseType databaseType = flowContext.checkInstanceData(DatabaseType.class);

        switch (databaseType){
            case H2:{flowContext.executeFlowList(new SetH2DataSourceFlow());}break;
            case SQLite:{flowContext.executeFlowList(new SetSQLiteDataSourceFlow());}break;
            case Mysql:{flowContext.executeFlowList(new SetMySQLDataSourceFlow());}break;
            case MariaDB:{flowContext.executeFlowList(new SetMariaDBDataSourceFlow());}break;
            case Postgresql:{flowContext.executeFlowList(new SetPostgresDataSourceFlow());}break;
            case SQLServer:{flowContext.executeFlowList(new SetSQLServerDataSourceFlow());}break;
            default:{
                throw new IllegalArgumentException("目前不支持该数据库类型!数据库类型:"+databaseType.name());
            }
        }
    }

    private void setDAO(FlowContext flowContext){
        HikariDataSource hikariDataSource = (HikariDataSource) flowContext.checkData("hikariDataSource");

        DAO dao = QuickDAO.newInstance()
                .dataSource(hikariDataSource)
                .packageName("cn.schoolwow.quickdao.test.entity")
                .beforeAutomaticCreate("测试自动建表之前执行语句", d->{
                    d.rawSelect("select 1");
                })
                .afterAutomaticCreate("测试自动建表之后执行语句", d->{
                    d.rawSelect("select 2");
                })
//                .foreignKey(true)
                .build();
        flowContext.putInstanceData(dao, DAO.class, FlowContextDataRange.Context, FlowDataFeature.TemporaryData);
        SetDAOFlow.dao = dao;
    }
}
